import { createSlice } from '@reduxjs/toolkit'
const tokenKey = 'token'
const nickNameKey = 'nickName'
const userSlice = createSlice({
  name: 'uesrSlice',
  initialState: {
    token: sessionStorage.getItem(tokenKey) || '',
    nickName: sessionStorage.getItem(nickNameKey) || ''
  },
  reducers: {
    setToken: (state, action) => {
      // 设置 token ， 因为 reduxjs/toolkit 内置了 immer 库, 所以可以直接操作 state
      const { nickName, token } = action.payload
      state.token = token || ''
      state.nickName = nickName || ''
      sessionStorage.setItem(tokenKey, token)
      sessionStorage.setItem(nickNameKey, nickName)
    },
    removeToken: (state) => {
      // 移除 state 中的 token 
      state.token = ''
      state.nickName = ''
      sessionStorage.removeItem(tokenKey)
      sessionStorage.removeItem(nickNameKey)
    }
  }
})

// 将 action 和 reducers 暴露出去
export const { setToken, removeToken } = userSlice.actions

export default userSlice